using System;
using System.Text.Encodings.Web;
using System.Text.Unicode;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Mvc.ApplicationModels;
using Microsoft.AspNetCore.Mvc.Versioning;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace LdCms.Web
{
    using Autofac;
    using LdCms.Common.Extension;
    using LdCms.EF.DbConfig;
    using LdCms.EF.DbEntitiesContext;
    using LdCms.Plugins.UEditor;
    using LdCms.Web.Extensions;
    using LdCms.Web.MiddleWares;
    using LdCms.Web.Models;


    /// <summary>
    /// 
    /// </summary>
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
        public string AllowSameDomain = "AllowSameDomain";
        public IConfiguration Configuration { get; }
        public IHttpContextAccessor HttpContextAccessor { get; }
        /// <summary>
        /// 此方法由运行时调用。使用此方法将服务添加到容器。
        /// </summary>
        /// <param name="services"></param>
        public void ConfigureServices(IServiceCollection services)
        {
            //配置读写配置文件
            services.AddSingleton(Configuration);
            //获取数据库链接字符串
            services.Configure<ConnectionStrings>(Configuration.GetSection("ConnectionStrings"));
            //获取站点信息
            services.Configure<SiteConfig>(Configuration.GetSection("SiteConfig"));
            //设置允许同步
            services.Configure<IISServerOptions>(options =>
            {
                options.AllowSynchronousIO = true;
            });
            //lambda确定给定请求是否需要用户对非必需cookie的同意
            services.Configure<CookiePolicyOptions>(options =>
            {
                options.CheckConsentNeeded = context => false;
                //options.MinimumSameSitePolicy = SameSiteMode.None;
            });
            //配置 Session、Cookies、Cache
            services.AddDistributedMemoryCache();
            services.AddSession(options =>
            {
                options.Cookie.IsEssential = true;
                options.IdleTimeout = TimeSpan.FromSeconds(7200);
            });
            //数据库链接
            services.AddDbContext<LdCmsDbEntitiesContext>(options =>
            {
                options.UseSqlServer(Configuration.GetConnectionString("SqlServerConnection"));
            }, ServiceLifetime.Scoped);
            //配置http body
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            //配置上传文件大小，系统默信最大20M
            services.Configure<FormOptions>(options =>
            {
                options.MultipartBodyLengthLimit = 20971520; //最大长度100M
                options.KeyLengthLimit = 20971520;
            });
            //百度在线编辑器UEditor 配置
            services.AddUEditorService("appsettings.UEditorConfig.json", false);
            //格式化JSON时间、Unicode转换中文
            services.AddControllersWithViews().AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.Converters.Add(new DateTimeConverter());
                options.JsonSerializerOptions.Converters.Add(new DateTimeNullConverter());
                options.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
            });
            //跨域请求 API
            var urls = Configuration["AppCors:Url"].Split(",");
            services.AddCors(options =>
            {
                options.AddPolicy(AllowSameDomain, builder => builder.AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowCredentials()
                    .WithOrigins(urls)
                );
            });
            //API版本控制DI
            services.AddApiVersioning(options =>
            {
                options.ApiVersionReader = new MediaTypeApiVersionReader();
                options.AssumeDefaultVersionWhenUnspecified = true;
                options.ApiVersionSelector = new CurrentImplementationApiVersionSelector(options);
            });
            //注册Swagger生成器，定义一个和多个Swagger 文档
            //services.AddSwaggerGen(c =>
            //{
            //    c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API v1", Version = "v1" });
            //});

            services.AddControllersWithViews(options =>
            {
                options.Conventions.Add(new RouteTokenTransformerConvention(new SlugifyParameterTransformer()));  //路由使用参数转换程序自定义标记替换
            }).AddNewtonsoftJson();

        }
        /// <summary>
        /// 此方法由运行时调用。使用此方法配置HTTP请求管道。
        /// </summary>
        /// <param name="app"></param>
        /// <param name="env"></param>
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHost host)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            ////启用中间件服务生成Swagger作为JSON终结点
            //app.UseSwagger();
            ////启用中间件服务对swagger-ui，指定Swagger JSON终结点
            //app.UseSwaggerUI(c =>
            //{
            //    c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
            //});

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();
            app.UseRouting();
            app.UseAuthorization();
            app.UseAuthentication();

            #region 设置

            //设置Request.Body
            app.Use(next => context =>
            {
                context.Request.EnableBuffering();
                context.Request.Body.Seek(0, 0);
                return next(context);
            });
            #endregion

            #region 中间件
            //异常处理中间件
            app.UseMiddleware(typeof(ExceptionHandlerMiddleWare));
            #endregion

            #region 扩展
            //HttpContext 扩展
            app.UseStaticHttpContext();
            #endregion

            //设置跨域
            app.UseCors(AllowSameDomain);

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
        /// <summary>
        /// Autofac容器注册
        /// </summary>
        /// <param name="builder"></param>
        public void ConfigureContainer(ContainerBuilder builder)
        {
            builder.RegisterModule(new AutofacModule());
        }
    }
}
